package com.example.heipictureserver.controller;

/*
 *@Description 用户控制器
 *@Author bwg
 *@Date 2025/1/17 20:07
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.heipictureserver.annotation.AuthCheck;
import com.example.heipictureserver.common.BaseResponse;
import com.example.heipictureserver.common.ResultUtils;
import com.example.heipictureserver.constant.UserConstant;
import com.example.heipictureserver.exception.BusinessException;
import com.example.heipictureserver.exception.ErrorCode;
import com.example.heipictureserver.exception.ThrowUtils;
import com.example.heipictureserver.modal.domain.User;
import com.example.heipictureserver.modal.dto.user.*;
import com.example.heipictureserver.modal.vo.LoginUserVO;
import com.example.heipictureserver.modal.vo.UserVO;
import com.example.heipictureserver.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

 @Resource
 private UserService userService;

 /**
  * 用户注册
  * @param userRegisterRequest
  * @return
  */
 @PostMapping("/register")
 public BaseResponse<String> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
  ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
  String userAccount = userRegisterRequest.getUserAccount();
  String userPassword = userRegisterRequest.getUserPassword();
  String checkPassword = userRegisterRequest.getCheckPassword();
  String result = userService.userRegister(userAccount, userPassword, checkPassword);
  return ResultUtils.success(result);
 }

 /**
  * 用户登录
  * @param userLoginRequest
  * @param request
  * @return
  */
 @PostMapping("/login")
 public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
  ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
  String userAccount = userLoginRequest.getUserAccount();
  String userPassword = userLoginRequest.getUserPassword();
  LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
  return ResultUtils.success(loginUserVO);
 }

 /**
  * 获取当前登录用户
  * @param request
  * @return
  */
 @GetMapping("/get/login")
 public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
  User loginUser = userService.getLoginUser(request);
  return ResultUtils.success(userService.getLoginUserVO(loginUser));
 }

 /**
  * 用户注销
  * @param request
  * @return
  */
 @PostMapping("/logout")
 public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
  ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
  boolean result = userService.userLogout(request);
  return ResultUtils.success(result);
 }

 /**
  * 创建用户
  */
 @PostMapping("/add")
 @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
 public BaseResponse<String> addUser(@RequestBody UserAddRequest userAddRequest) {
  ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
  User user = new User();
  BeanUtil.copyProperties(userAddRequest, user);
  // 默认密码
  final String DEFAULT_PASSWORD = "12345678";
  String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
  user.setUserPassword(encryptPassword);
  // 插入数据库
  boolean result = userService.save(user);
  ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
  return ResultUtils.success(user.getId());
 }

 /**
  * 根据 id 获取用户（仅管理员）
  */
 @GetMapping("/get")
 @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
 public BaseResponse<User> getUserById(String id) {
  ThrowUtils.throwIf(StrUtil.isEmpty(id), ErrorCode.PARAMS_ERROR);
  User user = userService.getById(id);
  ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
  return ResultUtils.success(user);
 }

 /**
  * 根据 id 获取包装类
  */
 @GetMapping("/get/vo")
 public BaseResponse<UserVO> getUserVOById(String id) {
  BaseResponse<User> response = getUserById(id);
  User user = response.getData();
  return ResultUtils.success(userService.getUserVO(user));
 }

 /**
  * 删除用户
  */
 @DeleteMapping("/delete/{id}")
 @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
 public BaseResponse<Boolean> deleteUser(@PathVariable String id) {
  if (id == null || StrUtil.isBlank(id)) {
   throw new BusinessException(ErrorCode.PARAMS_ERROR);
  }
  boolean b = userService.removeById(id);
  return ResultUtils.success(b);
 }

 /**
  * 更新用户
  */
 @PutMapping("/update")
 @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
 public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
  if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
   throw new BusinessException(ErrorCode.PARAMS_ERROR);
  }
  User user = new User();
  BeanUtils.copyProperties(userUpdateRequest, user);
  boolean result = userService.updateById(user);
  ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
  return ResultUtils.success(true);
 }

 /**
  * 分页获取用户封装列表（仅管理员）
  *
  * @param userQueryRequest 查询请求参数
  */
 @PostMapping("/list/page/vo")
 @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
 public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
  ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
  long current = userQueryRequest.getCurrent();
  long pageSize = userQueryRequest.getPageSize();
  Page<User> userPage = userService.page(new Page<>(current, pageSize),
          userService.getQueryWrapper(userQueryRequest));
  Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
  List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
  userVOPage.setRecords(userVOList);
  return ResultUtils.success(userVOPage);
 }

 /**
  * 用户修改信息
  * @param userEditRequest
  * @param request
  * @return
  */
 @PutMapping("/edit")
 public BaseResponse<Boolean> editUser(@RequestBody UserEditRequest userEditRequest,HttpServletRequest request) {
  ThrowUtils.throwIf(userEditRequest == null, ErrorCode.PARAMS_ERROR);
  User user = userService.getLoginUser(request);
  BeanUtils.copyProperties(userEditRequest, user);
  boolean result = userService.updateById(user);
  ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
  return ResultUtils.success(true);
 }
}
